# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jhkim

import collections
import os
import glob
import pandas
from absl import app, flags
from coin.exchange.kr_rest.product.product_impl import generate_product_from_str2
from coin.strategy.mm.tool.feed_stat_util import enumerate_volume_trend


def main(_):
  dfs = []
  datestr = "20200425"
  dt = pandas.DatetimeIndex([datestr]).to_pydatetime()[0]
  dfs = []
  for nametuple, df in enumerate_volume_trend(dt.strftime("%Y%m%d"), dt.strftime("%Y%m%d")):
    dfs.append(df)
  df = pandas.concat(dfs, axis=0).reset_index(drop=True)
  df = df.sort_values('total_notional', ascending=False).reset_index(drop=True)

  os.makedirs(flags.FLAGS.out_dir, exist_ok=True)
  with open(f"{flags.FLAGS.out_dir}/symbol_rank.txt", 'w') as wfile:
    print(df.to_string(), file=wfile)

  rows = []
  outs = []
  outs2 = collections.defaultdict(list)
  for i, row in df.iterrows():
    try:
      product = generate_product_from_str2(row['market_type'],
                                           row['exchange'],
                                           None,
                                           row['symbol'],
                                           dt)
    except Exception as exc:
      print(exc)
      continue
    exchange = row['exchange']
    subsymbol = (product.subscription_symbol
                 if hasattr(product, "subscription_symbol") else product.symbol)
    subsymbol = subsymbol.replace("CURRENT_", "").replace("THIS_", "")
    files = glob.glob(
        f"{flags.FLAGS.lm_export_path}/pic"
        f"/*OneBigSampler2*Y.3s*{exchange}*{subsymbol}*quantile.png")
    if len(files) == 0:
      rows.append(row)
      continue
    else:
      istr = "%03d" % i
      frompic = files[0]
      outpic = os.path.join(f"{flags.FLAGS.out_dir}/{istr}_{exchange}_{subsymbol}.png")
      os.system(f"cp {frompic} {outpic}")
      outs.append(outpic)
      outs2[f"{row.market_type}_{row.exchange}"].append(outpic)
  print("Not Available Products")
  with open(f"{flags.FLAGS.out_dir}/symbol_rank_not_available.txt", 'w') as wfile:
    print(pandas.DataFrame(rows).to_string(), file=wfile)
  print(pandas.DataFrame(rows).to_string())
  cmd = f"convert {' '.join(outs)} {flags.FLAGS.out_dir}/out.pdf"
  os.system(cmd)
  for key, vals in outs2.items():
    cmd = f"convert {' '.join(vals)} {flags.FLAGS.out_dir}/{key}.pdf"
    os.system(cmd)


if __name__ == '__main__':
  flags.DEFINE_string('lm_export_path', 'python/lm_export', '')
  flags.DEFINE_string('out_dir', 'symbol_rank', '')
  app.run(main)
